package com.lian.community.async;
import com.alibaba.fastjson.JSON;
import com.lian.community.constant.EventType;
import com.lian.community.dao.redis.JedisDAO;
import com.lian.community.util.RedisKeyUtil;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;


/**
 * 事件消费者：把event分发到不同的handler上
 */
@Service
public  class EventComsumer implements InitializingBean, ApplicationContextAware{

    @Autowired
    JedisDAO jedisDAO;

    private static final org.slf4j.Logger logger = LoggerFactory.getLogger(EventComsumer.class);

    private ApplicationContext applicationContext;

    private static int COMSUER_TIMEOUT = 24*3600;

    private Map<EventType, List<EventHandler>> config = new HashMap<>();


    @Override
    public void afterPropertiesSet() throws Exception{
        Map<String, EventHandler> beans = applicationContext.getBeansOfType(EventHandler.class);
        if(beans != null){
            for(Map.Entry<String, EventHandler> entry : beans.entrySet()){
                List<EventType> eventTypes = entry.getValue().geSupportEvent();

                // 找到自己所关系的event后，把eventType与自己对应存储起来
                for (EventType type : eventTypes){
                    if(!config.containsKey(type)){
                        config.put(type, new ArrayList<EventHandler>());
                    }
                    config.get(type).add(entry.getValue());
                }

            }
        }

        ExecutorService fixTHreadPool = Executors.newFixedThreadPool(5);
        fixTHreadPool.submit(new Runnable() {

//        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                while (true) {
                    String key = RedisKeyUtil.getEventKey();
                    List<String> events = jedisDAO.brpop(24*3600,key);
                    for (String message : events) {
                        if (message.equals(key)) {
                            continue;
                        }
                        EventModel eventModel = JSON.parseObject(message, EventModel.class);
                        if (!config.containsKey(eventModel.getEventType())) {
                            System.out.println("wrong event!");
                            logger.error("不能识别的事件！");
                            continue;
                         }

                        for (EventHandler handler : config.get(eventModel.getEventType())) {
                            handler.doHandler(eventModel);
                        }
                    }
                }
            }
        });
//        thread.run();
    }


    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;

    }
}
